package de.slothsoft.commons.swing;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;

import javax.swing.JPanel;

/**
 * Stretches a background image over the entire width of the panel
 */

public class ImagePanel extends JPanel {

	// TODO: the ImagePanel's preferred size is the background images size
	// TODO: scale if the image is other than the panels scale
	// TODO: check if this class belongs to the commons

	private static final long serialVersionUID = 1L;
	private Image backgroundImage;

	public Image getBackgroundImage() {
		return this.backgroundImage;
	}

	public void setBackgroundImage(Image backgroundImage) {
		this.backgroundImage = backgroundImage;
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		if (this.backgroundImage != null) {
			Dimension d = getSize();
			g.drawImage(this.backgroundImage, 0, 0, d.width, d.height, this);
		}
	}

	public Point getProportions() {

		if (this.backgroundImage != null) {
			int h = this.backgroundImage.getHeight(null);
			int w = this.backgroundImage.getWidth(null);
			return new Point(w, h);
		}
		return new Point(1, 1);
	}

	@Override
	public Dimension getPreferredSize() {
		// TODO: make the scaling work
		Dimension d = super.getPreferredSize();
		Point p = getProportions();
		d.height = d.width * p.y / p.x;
		return d;

	}
}
